package com.example.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.model.RegisterTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RegisterActivity extends AppCompatActivity {
    String verificationCode = "";
    String username;
    TextView textViewSendCode;
    CountDownTimer countDownTimer;
    EditText usernameEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        textViewSendCode = findViewById(R.id.textViewSendCode);
        usernameEditText = findViewById(R.id.editTextPhoneNumber);

        textViewSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = usernameEditText.getText().toString();
                sendSMS();
            }
        });

        ImageView imgBack = findViewById(R.id.imageView_arrow);
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Button buttonRegister = findViewById(R.id.buttonRegister);
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText passwordEditText = findViewById(R.id.editTextPassword);
                EditText editTextConfirmPassword = findViewById(R.id.editTextConfirmPassword);
                EditText editTextVerificationCode = findViewById(R.id.editTextVerificationCode);

                String password1 = passwordEditText.getText().toString();
                String password2 = editTextConfirmPassword.getText().toString();
                String code = editTextVerificationCode.getText().toString();

                if (code.equals(verificationCode)) {
                    if (!password1.equals(password2)) {
                        Toast.makeText(RegisterActivity.this, "两次输入的密码不相同", Toast.LENGTH_SHORT).show();
                    } else {
                        Context context = getApplicationContext();
                        RegisterTask registerTask = new RegisterTask(context, username, password1);
                        registerTask.execute();
                    }
                } else {
                    Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void sendSMS() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = "http://39.107.92.86:5000/sendsms?phone_number=" + username;

                    URL serverUrl = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection();
                    connection.setRequestMethod("GET");
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();

                    JSONObject jsonObject = new JSONObject(response.toString());
                    verificationCode = jsonObject.optString("code");

                    if (!verificationCode.isEmpty()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                startTimer();
                                Toast.makeText(RegisterActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this, "验证码发送失败，请重试", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    connection.disconnect();
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(RegisterActivity.this, "请求失败，请检查网络连接", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    private void startTimer() {
        textViewSendCode.setEnabled(false);

        countDownTimer = new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
                long seconds = millisUntilFinished / 1000;
                textViewSendCode.setText("重试 (" + seconds + "s)");
            }

            public void onFinish() {
                textViewSendCode.setText("发送验证码");
                textViewSendCode.setEnabled(true);
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
